<?php

namespace Plu\qdh\Services;

use Httpful\Request;
use Plu\qdh\Services\ServiceBase;
use Plu\qdh\Models\App\Project;
use Plu\qdh\Models\App\Platform;
use Plu\qdh\Models\App\Product;

class ProductService extends ServiceBase {
    // 栏目详情 STRING
    const PLATFORM_INFO = "platform:info:%s";
    // 商品详情 STRING
    const PRODUCT_INFO  = "product:info:%s";
    // 项目详情 STRING
    const PROJECT_INFO  = "projtct:info:%s";
    // 栏目项目对应关系 HASH
    const PLATFORM_PROJECT_REDIS_KEY = 'platform:%s:projects';
    // 项目产品对应关系 HASH
    const PROJECT_PRODUCT_REDIS_KEY  = 'project:%s:products';

    private $_platformId;

    private $_projectId;

    private $_productNo;

    private $_redis;


    public function setProductNo($productNo) {
        $this->_productNo = $productNo;
    }

    public function setPlatformId($platformId) {
        $this->_platformId = $platformId;
    }

    public function setProjectId($projectId) {
        $this->_projectId = $projectId;
    }

    public function __construct() {
        $this->_redis = $this->getRedis('qdh');
    }


    public function getAllPlatform() {
        $items = Platform::getItems();
        return $items;
    }

    // 创建 编辑栏目
    public function addPlatForm($platformId, $platformName) {
        $model = Platform::getItemById($platformId);
        if (!$model) {
            $model = new Platform;
        }
        $model->platformName = $platformName;
        $model->createTime   = time();
        if ($model->save()) {
            $redis = $this->_redis;
            $redisKey  = sprintf(self::PLATFORM_INFO, $model->id);
            $cacheData =  json_encode($model->toArray());
            $redis->set($redisKey, $cacheData);
            return true;
        }
        return false;
    }

    // 删除栏目
    public function delPlatForm($platformId) {
        $model   = Platform::getItemById($platformId);
        $modelId = $model->id; 
        if ($model->delete()) {
            $redis = $this->_redis;
            $redisKey  = sprintf(self::PLATFORM_INFO, $modelId);
            $redis->del($redisKey);


            return true;
        }
        return false;
    }

    // 获取项目列表
    public function getAllProject() {
        $redis = $this->_redis;
        $items = $this->getProjectList();
        if (!empty($items)) {
            foreach ($items as $index => $item) {
                $items[$index]['pics']      = explode(",", $item['imgs']); 
                $items[$index]['platform']  = json_decode($redis->get(sprintf(self::PLATFORM_INFO, $item['platformId'])), true);
                $items[$index]['startTime'] = gmdate('Y-m-d\TH:i:s\Z', $item['startTime']);
                $items[$index]['endTime']   = gmdate('Y-m-d\TH:i:s\Z', $item['endTime']);
                $items[$index]['status']    = (int)$item['status'];
                $items[$index]['products']  = $this->getProductsByProject($item['id']);
            }
            return $items;
        }
        return [];
    }

    public function getProjectList() {
        $items = Project::getItems($this->_platformId);
        return $items;
    }

    // 创建 编辑项目
    public function addProject($projectId, $productData) {
        //$productData = json_decode($productData, true);
        $item = Project::getItemById($projectId);
        if (!$item) {
            $item = new Project;
            $item->status = \ProjectConst::PROJECT_STATUS['off'];
        }

        $item->projectName = $productData['projectName'];
        $item->scenicName  = $productData['scenicName'];
        $item->projectDescription = $productData['projectDescription'];
        $item->longitude = $productData['longitude'];
        $item->latitude  = $productData['latitude'];
        $item->cover     = $productData['cover'];
        $item->startTime = strtotime($productData['startTime']);
        $item->endTime   = strtotime($productData['endTime']);
        $item->projectTips = $productData['projectTips'];
        $item->phone = $productData['phone'];
        $item->projectPrompt = $productData['projectPrompt'];
        $item->imgs = join(",", $productData['pics']);
        $item->platformId = $productData['platformId'];
        $item->createTime = time();

        $save = $item->save();
        if ($save) {
            $this->setProjectRedisCache($item->id, $item->platformId, $item->toArray());
            return true;
        }

        return false;
    }

    // 删除项目
    public  function delProject($projectId, $productData) {
        $productData = json_decode($productData, true);
        $item = Project::getItemById($projectId);
        $platformId = $item->platformId;
        if ($item->delete()) {
            // 删除项目信息缓存
            $this->delProjectRedisCache($projectId);
            // 删除产品绑定关系
            $redisKey = sprintf(self::PROJECT_PRODUCT_REDIS_KEY, $projectId);
            $this->_redis->del($redisKey);
            // 删除栏目绑定关系
            $redisKey = sprintf(self::PLATFORM_PROJECT_REDIS_KEY, $platformId);
            $this->_redis->hDel($redisKey, $projectId);

            return true;
        }

        return false;
    }

    // 删除项目缓存信息
    private function delProjectRedisCache($projectId) {
        $redisKey  = sprintf(self::PROJECT_INFO, $projectId);
        $this->_redis->del($redisKey, $data);
    }

    // 缓存项目信息 TODO 缓存 GEO
    private function setProjectRedisCache($projectId, $platformId, $projectData) {
        $redisKey  = sprintf(self::PROJECT_INFO, $projectId);
        $data      = json_encode($projectData);
        $this->_redis->set($redisKey, $data);
    }

    // 设置项目与栏目关系
    public function setPlatformProject($platformId, $projectId) {
        $item = Project::getItemById($projectId);
        $item->status = \ProjectConst::PROJECT_STATUS['on'];
        if ($item->save()) {
            $redisKey = sprintf(self::PLATFORM_PROJECT_REDIS_KEY, $platformId);
            $data     = json_encode($item);
            $redis    = $this->_redis;
            $redis->hSet($redisKey, $projectId, $data);
            return true;
        }
        return false;
    }

    // 移除项目与栏目关系
    public function delPlatformProject($platformId, $projectId) {
        $item = Project::getItemById($projectId);
        $item->status = \ProjectConst::PROJECT_STATUS['off'];
        if ($item->save()) {
            $redisKey = sprintf(self::PLATFORM_PROJECT_REDIS_KEY, $platformId);
            $redis    = $this->_redis;
            $redis->hDel($redisKey, $projectId);
            return true;
        }
        return false;
    }

    public function getProjectInfo($projectId) {
        $redisKey  = sprintf(self::PROJECT_INFO, $projectId);
        $data      = $this->_redis->get($redisKey);
        if ($data) {
            $res = json_decode($data, true);
            $res['startTime'] = date('Y-m-d', $res['startTime']);
            $res['endTime']   = date('Y-m-d', $res['endTime']);
            $res['imgs']      = explode(",", $res['imgs']);
            $products = $this->getProductsByProject($projectId);
            $format = [];
            foreach($products as $product) {
                $r = [
                    'productName' => $product['productName'],
                    'customPrize' => $product['customPrize'],
                    'productNo'   => $product['productNo']
                ];
                $format[] = $r;
            }
            $res['products'] = $format;
            return $res;
        }
        return [];
    }

    public function getProjectsByPlatform($platformId) {
        $redisKey = sprintf(self::PLATFORM_PROJECT_REDIS_KEY, $platformId);
        $datas    = $this->_redis->hGetAll($redisKey);
        $res = [];
        foreach  ($datas as $index => $values) {
            $r  = json_decode($values, true);
	        //价格最低的产品展示在项目外
            $projectProducts = $this->getProductsByProject($r['id']);
            $p = [];
            foreach ($projectProducts as $product) {
                $p[] = $product['customPrize'];
            }
            $minPrice = min($p);

	        $format = [
                'id'          => $r['id'],
                'projectName' => $r['projectName'],
                'cover'       => $r['cover'],
                'longitude'   => $r['longitude'],
                'latitude'    => $r['latitude'],
                'price'       => $minPrice?$minPrice:0,
		        'distance'    => '1km'
            ];
            $res[] = $format;
        }
        return $res;
    }

    // 创建 编辑产品
    public function addProduct($productData) {
        $projectId   = $productData['projectId'];
        $productNo   = $productData['productNo'];
        $createProduct = $this->createProduct($productNo, $productData);
        if ($createProduct) {
            $productData['projectId'] = $projectId;
	        $this->cacheProduct($productNo, $productData);
            $this->setProductRelation($projectId, $productNo);
            return true;
        }
        return false;
    }

    // 第三方商品入库 TODO
    private function createProduct($productNo, $productData) {
        $time = date('Y-m-d', time());
        $item = Product::getItemByproductNo($productNo);
        if (!$item) {
            $item = new Product;
            $item->createTime = $time;
        }
        foreach ($productData as $key => $value) {
            $item->$key = $value;
        } 
        $item->updateTime = $time;
        if ($item->save()) {
            return true;
        }
        return false;
    }


    // 产品项目关系
    private function setProductRelation($projectId, $productNo) {

        $redisKey = sprintf(self::PROJECT_PRODUCT_REDIS_KEY, $projectId);
        $redis    = $this->_redis;
        $redis->sAdd($redisKey, $productNo);
  	
	    //价格最低的产品展示在项目外
        $projectProducts = $this->getProductsByProject($projectId);
        $r = [];
        foreach ($projectProducts as $product) {
            $r[] = $product['customPrize'];
        }

        $minPrice = min($r);
        $projectRedisKey = sprintf(self::PROJECT_INFO, $projectId);
        $projectInfo = $redis->get($projectRedisKey);
        $projectInfo = json_decode($projectInfo, true);
        $projectInfo['price'] = $minPrice;
        $projectInfo = json_encode($projectInfo);
	    $redis->set($projectRedisKey, $projectInfo); 
   }


    // 删除产品项目关系
    public function delProductRelation($projectId, $productNo) {
        $redisKey = sprintf(self::PROJECT_PRODUCT_REDIS_KEY, $projectId);
        $redis    = $this->_redis;
        $redis->sRem($redisKey, $productNo);
    }

    // 缓存产品信息
    public function cacheProduct($productNo, $productData) {
        $redisKey = sprintf(self::PRODUCT_INFO, $productNo);
        $data     = json_encode($productData);
        $this->_redis->set($redisKey, $data);
    }

    public function getProductIdsByProject($projectId) {
        $redisKey = sprintf(self::PROJECT_PRODUCT_REDIS_KEY, $projectId);
        $data     = $this->_redis->sMembers($redisKey);
        return $data;
    }

    // 获取项目下所有产品
    public function getProductsByProject($projectId) {
        $datas = $this->getProductIdsByProject($projectId);
        if (!empty($datas)) {
            $format = [];
            foreach ($datas as $productNo) {
                $r = $this->_redis->get(sprintf(self::PRODUCT_INFO, $productNo));
                $r = json_decode($r, true);
                $format[] = $r;
            }
            return $format;
        }
        return [];
    }

    // 获取产品详情
    public function getProductDetail($productNo) {
        $r = $this->_redis->get(sprintf(self::PRODUCT_INFO, $productNo));
        $r = json_decode($r, true);
        if (!$r['refoundable']) {
            $r['refoundable'] = "0";
        }
        return $r;
    }








}
